import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const router = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
router.interceptors.request.use(
  (config) => {
    // do something before request is sent

    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${getToken()}`
    }
    return config
  },
  (error) => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
router.interceptors.response.use(

  (response) => {
    const { msg, data, code } = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (code === 10000) {
      return data
    } else {
      Message.error({ type: 'error', msg })
      return msg
    }
  },
  async(error) => {
    if (error.status === 401) {
      Message.error('登录过期了')
      await store.dispatch('user/logout')
      router.replace('/login')
    } else {
      Message.error(error.message)
    }
    return Promise.reject(error)
  }
)

export default router
